<script>
	// 更新APP用的
	// #ifdef APP-PLUS
	import MAPPUpdate from '@/uni_modules/mc-ui/components/m-app-update/js_sdk/appUpdate.js';
	// #endif
	// var jpushModule = uni.requireNativePlugin("JG-JPush");
	import options from '@/common/config/msgToast/options.js';
	import initLevitatedSphere from '@/common/config/msgToast/levitatedSphere.js';
	import {
		mapState
	} from 'vuex'
	//#ifdef APP-ANDROID
	var ZZDelayStart = uni.requireNativePlugin('ZZ-Delay-Start');

	ZZDelayStart.setDelay({
		'delay': 5,
	})
	//#endif
	export default {
		data() {
			return {
				activeCtx: null,
				_onNetworkStatusChangeHandler: null,
			}
		},
		computed: mapState({
			openMsgBtnType(state) { // 全局按钮-消息按钮是否展示
				return state.systemConfig.msgConfig.openMsgBtnType
			},
			msgBtnIsHide(state) { // 页面级控制消息按钮是否隐藏
				return state.systemConfig.msgConfig.msgBtnIsHide
			},
			isLogin(state) {
				return state.systemConfig.isLogin
			},
			hasMsg(state) { // 是否有新消息
				return state.systemConfig.msgConfig.hasMsg
			},
		}),
		watch: {
			hasMsg: {
				handler(nval) {
					if (nval) {
						this.activeCtx.updateImage('/static/image/Img/newMsg.png');
					} else {
						this.activeCtx.updateImage('/static/image/Img/msg.png');

					}
				}
			},
			msgBtnIsHide: {
				handler(nVal) {
					if (this.openMsgBtnType) {
						if (nVal != true) {
							this.activeCtx.show();
						} else {
							if (this.activeCtx) {
								this.activeCtx.hide();
							}
						}
					} else {
						if (this.activeCtx) {
							this.activeCtx.hide();
						}
					}
				}
			},
			openMsgBtnType: {
				handler(nVal, oVal) {
					if (nVal == true) {
						// Data = this.activeCtx;
						// 根据当前路由判断是否显示消息按钮
						const pages = getCurrentPages()
						const currentPage = pages[pages.length - 1]
						const route = currentPage.route // 获取路由路径
						if (route.indexOf("pages/Message/Message") == -1) {
							this.activeCtx.show();
						}

					} else {
						if (this.activeCtx) {
							this.activeCtx.hide();
							// Data = null;
						}
					}
					// console.log(Data);

					// this.$store.commit('ChangeAndSetStateData', {
					// 	Name1: 'systemConfig.msgConfig.activeCtx',
					// 	data: Data,
					// });

				}
			},
			isLogin: {
				handler(nval, oval) {
					if (nval == true) {
						try {
							if (uni.getSystemInfoSync().platform == "ios") {

								// 请求定位权限
								// let locationServicesEnabled = jpushModule.locationServicesEnabled()
								// let locationAuthorizationStatus = jpushModule.getLocationAuthorizationStatus()
								// console.log('locationServicesEnabled', locationServicesEnabled)
								// console.log('locationAuthorizationStatus', locationAuthorizationStatus)
								// if (locationServicesEnabled == true && locationAuthorizationStatus < 3) {
								// 	jpushModule.requestLocationAuthorization((result) => {
								// 		console.log('定位权限', result.status)
								// 	})
								// }



								// jpushModule.requestNotificationAuthorization((result) => {
								// 	console.log(result)
								// 	let status = result.status
								// 	if (status < 2) {
								// 		// uni.showToast({
								// 		// 	icon: 'none',
								// 		// 	title: '您还没有打开通知权限',
								// 		// 	duration: 3000
								// 		// })
								// 	}
								// })
							}

							// jpushModule.getRegistrationID(result => {
							// 	// let registerID = result.registerID
							// })

							// jpushModule.initJPushService();
							// jpushModule.setLoggerEnable(true);
							// jpushModule.addConnectEventListener(result => {
							// 	let connectEnable = result.connectEnable
							// 	uni.$emit('connectStatusChange', connectEnable)
							// });


							// // 接收消息（通知栏消息 + 应用内接收消息）
							// jpushModule.addNotificationListener(result => {
							// 	let notificationEventType = result.notificationEventType
							// 	let messageID = result.messageID
							// 	let title = result.title
							// 	let content = result.content
							// 	let extras = result.extras
							// 	console.log(result)

							// 	if (notificationEventType == 'notificationArrived') { // 收到消息

							// 	} else if (notificationEventType == 'notificationOpened') {
							// 		// 手动点击消息
							// 		jpushModule.setBadge(0);
							// 	}
							// });

							// // 自定义消息事件回调-监听 Portal 发送的自定义消息
							// jpushModule.addCustomMessageListener(result => {
							// 	// let type = result.type
							// 	// let messageType = result.messageType
							// 	// let content = result.content
							// });

							// // 本地通知事件回调
							// jpushModule.addLocalNotificationListener(result => {
							// 	let notificationEventType = result.notificationEventType;
							// 	if (notificationEventType == 'notificationOpened') {
							// 		// 手动点击消息
							// 		uni.navigateTo({
							// 			url: '/pages/Message/Message' + '?nav=1'
							// 		});
							// 	};
							// });

							// // jpushModule.addGeofenceListener(result => {
							// // 	let code = result.code
							// // 	let type = result.type
							// // 	let geofenceId = result.geofenceId
							// // 	let userInfo = result.userInfo
							// // 	console.log(result)
							// // 	uni.showToast({
							// // 		icon: 'none',
							// // 		title: '触发地理围栏',
							// // 		duration: 3000
							// // 	})
							// // })

							// jpushModule.setIsAllowedInMessagePop(true)
							// // jpushModule.pullInMessage(result => {
							// // 	let code = result.code
							// // 	console.log(code)
							// // })

							// // 应用内-插屏消息
							// jpushModule.addInMessageListener(result => {
							// 	console.log(result)
							// 	let eventType = result.eventType
							// 	let messageType = result.messageType
							// 	let content = result.content
							// 	console.log('inMessageListener', eventType, messageType, content)
							// })
						} catch (e) {
							//TODO handle the exception
						}
					}
				},
				deep: true,
				immediate: true
			}
		},
		onLaunch: function() {
			let that = this;

			// console.log('App Launch')
			// console.log(this.$store.state.systemConfig.msgConfig.openMsgBtnType)

			// 获取全局按钮实例对象
			const activeCtx = initLevitatedSphere(options, this.clickHandler, false);

			this.activeCtx = activeCtx;
			// 存储到vuex
			this.$store.commit('ChangeAndSetStateData', {
				Name1: 'systemConfig.msgConfig.activeCtx',
				data: activeCtx,
			});

		},
		onShow: function() {
			// console.log('App Show')
			if (!this._onNetworkStatusChangeHandler) {
				this._onNetworkStatusChangeHandler = (res) => {
					if (res.networkType == 'none') {
						uni.showToast({
							title: '网络连接不可用',
							icon: 'error'
						});
					} else {
						uni.hideToast();
						uni.hideLoading();
					}
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'systemConfig.netWorkinfo',
						data: {
							networkType: res.networkType,
							isConnected: res.networkType !== 'none',
						},
					});
				};
				// 首次获取（可选，防止状态丢失）
				uni.getNetworkType({
					success: this._onNetworkStatusChangeHandler,
				});
				// 监听后续变化
				uni.onNetworkStatusChange(this._onNetworkStatusChangeHandler);
			}

			// 获取本地应用资源版本号
			// plus.runtime.getProperty(plus.runtime.appid, (inf) => {
			// 	console.log(inf)
			// })
			if (uni.getStorageSync('Allow_Restart')) {

				if (uni.getStorageSync('HiddenTime')) {
					let time = 1000 * 60 * 60;
					if (Number(new Date()) - Number(uni.getStorageSync('HiddenTime')) > time) {
						uni.removeStorageSync('HiddenTime');
						// 当关闭达到一定时长，重启应用
						plus.runtime.restart();
					}
				}
			}

		},
		onHide: function() {
			// console.log('App Hide')
			console.log('App Hide')
			uni.setStorageSync('HiddenTime', JSON.stringify(Number(new Date())))

			if (this._onNetworkStatusChangeHandler) {
				uni.offNetworkStatusChange(this._onNetworkStatusChangeHandler);
			}
		},
		onLoad() {
			Vue.config.errorHandler = function(err, vm, info) {
				console.error('Vue全局错误捕获:', err, info);
			};
		},
		created() {},
		mounted() {
			let that = this;

			uni.$on("updateApp", function(row) {
				console.log(row);
				const {
					from = ''
				} = row;

				let os = plus.os.name;
				let type = process.env.NODE_ENV !== 'development' && os != 'iOS';
				if (type) {
					MAPPUpdate(true,
						(res) => {
							console.log(res);
							that.$utils.hideLoading();
						},
						(ret) => { // 当前点击的按钮
							console.log(ret);
							that.$utils.hideLoading();
							switch (ret) {
								case 'cancel':
								case 'mask':
									if (from == 'login') {
										// 当取消升级的时候，去触发历史路由记录
										let ActiveModuleStartType = that.$store.state.appConfigInfo
											.ActiveModuleStartType;

										let str = uni.getStorageSync('ActiveModule');
										// 判断是否开机自启
										if (ActiveModuleStartType && str) {
											// 通知页面跳转
											uni.$emit("allowToNavgate")
										}


									}

									break;
								default:
									break;
							}
						});

				}
			})
		},
		onUnload() {
			// 卸载通知页面跳转
			uni.$off("allowToNavgate");

			uni.removeStorageSync('HiddenTime');
			uni.removeStorageSync('Allow_Restart');
			// 设备数据读取监听器卸载
			uni.$off("BluetoothData");
			uni.$off("changeDeivceStatus");
			this.$store.state.systemConfig.msgConfig.activeCtx.destroy();
			// 注销监听器
			if (this._onNetworkStatusChangeHandler) {
				uni.offNetworkStatusChange(this._onNetworkStatusChangeHandler);
			}
		},
		methods: {
			clickHandler(res) {
				if (res.type == 'click') {
					/* const pages = getCurrentPages()
					const currentPage = pages[pages.length - 1]
					const route = currentPage.route // 获取路由路径
					console.log('[RequestQueue] 页面路由:', route);
					console.log('click', res); */

					// 点击打开弹层选择前往消息或审批待办

					/* if (route.indexOf("pages/Message/Message") !== -1) {
						// 通知去刷新页面
						uni.$emit('msgReload', {
							status: 'reload'
						});
					} else { */
					this.$store.commit('ChangeAndSetStateData', {
						Name1: 'systemConfig.msgConfig.msgBtnIsHide',
						data: true
					});
					uni.navigateTo({
						url: '/pages/Message/Message' + '?nav=1'
					})
					/* } */


					// this.$store.state.systemConfig.msgConfig.activeCtx.hide();
				}
				// if (res.type == 'move') {

				// 	// console.log('move', res);
				// }
			}
		}
	}
</script>


<style lang="scss">
	/*每个页面公共css */
	@import '@/uni_modules/uview-ui/index.scss';
	// @import '@/static/assets/css/font/iconfont.css';


	/* #ifndef APP-NVUE */
	@import '@/uni_modules/mc-ui/index.scss';

	@font-face {
		font-family: CustomFontPlatform;
		src: url('@/static/assets/css/platformfont/iconfont.ttf') format('truetype');
		// src: url('http://mes.hzyc.org.cn:20050/icons/iconfont.ttf') format('truetype');
	}


	/* #endif*/
</style>